package com.example.demo_pc.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo_pc.util.DownloadImage;
import com.example.demo_pc.util.FileUtils;
import com.example.demo_pc.util.Reptiles;
import com.example.demo_pc.vo.ExceptionHandVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import us.codecraft.webmagic.Spider;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description :
 * @Author : wanghao
 * @Date: 2020-11-30 10:06
 */
@Controller
@RequestMapping("test")
public class TestController {
    private  final Logger logger = LoggerFactory.getLogger(TestController.class);


    @RequestMapping("pachong")
    public void pachong(String url,String outPath,String logPath,int num,int forNum){
        try {
            logger.info("开始");
            if (outPath==null || "".equals(outPath)){
                logger.info("参数为空");
                return;
            }
            
            String substring1 = outPath.substring(outPath.lastIndexOf("/") + 1);
            String prefixUrl = url.substring(0,url.lastIndexOf("/"));
            String substring = url.substring(url.lastIndexOf("/"));
            String content = FileUtils.getContent("\\d+", substring);
            int count = Integer.parseInt(content);
            List<String> urlList=new ArrayList<>();
            for (int i=0;i<forNum;i++){
                int res = count - i;
                String resUrl = prefixUrl + "/" + res;
                urlList.add(resUrl);
            }
            Reptiles h = new Reptiles(outPath,num);
            for (int i=0;i<forNum;i++){
                logger.info("=====================================================================");
                logger.info("第{}轮开始,地址:{}",i+1,urlList.get(i));
                h.setDownLoadList(new ArrayList<>());
                h.setExistList(new ArrayList<>());
                h.setErrorList(new ArrayList<>());
                //起始URL，开启的线程数为10个
                long startTime = System.currentTimeMillis();    //获取开始时间
                Spider.create(h).addUrl(urlList.get(i)).thread(1).run();
                long endTime = System.currentTimeMillis();    //获取结束时间
                logger.info("第{}轮下载耗时:{}" ,i+1,(endTime - startTime));
                FileUtils.writeContent(h.getDownLoadList(),logPath+"/catalog/"+substring1+"DownList.txt",urlList.get(i),FileUtils.formatDate(new Date()));
                FileUtils.writeContent(h.getExistList(),logPath+"/cumulativeExist.txt",urlList.get(i),FileUtils.formatDate(new Date()));
                FileUtils.writeContent(h.getErrorList(),logPath+"/cumulativeError.txt",urlList.get(i),FileUtils.formatDate(new Date()));
            }
            logger.info("结束");
        }catch (Exception e){
            logger.error("程序异常",e);
        }

    }
    @RequestMapping("exceptionHand")
    public void exceptionHand(String path,String logPath){
        logger.info("异常文件:{}",path);
        if (path==null){
            logger.error("文件不存在:{}",path);
            return;
        }
        long startTime = System.currentTimeMillis();    //获取开始时间
        List<String> errorList=new ArrayList<>();
        String content = FileUtils.readFileContent(path);
        content = content.replace("\\", "").replace("\"{", "{").replace("}\"", "}");
        List<ExceptionHandVo> exceptionHandVos = JSON.parseArray(content, ExceptionHandVo.class);
        for (ExceptionHandVo exceptionHandVo : exceptionHandVos) {
            logger.info("异常文件:{}",JSON.toJSONString(exceptionHandVo));
            long downStartTime = System.currentTimeMillis();    //获取开始时间
            //获取开始时间
            int flag=0;
            for (int i =1 ; i<=15;i++){
                boolean res = DownloadImage.downloadImage(exceptionHandVo.getSourcePath()+".jpg" , exceptionHandVo.getFileName(), exceptionHandVo.getOutPath(),i);
                if (res){
                    flag++;
                    break;
                }
                boolean result = DownloadImage.downloadImage(exceptionHandVo.getSourcePath()+".png" , exceptionHandVo.getFileName(), exceptionHandVo.getOutPath(),i);
                if (result){
                    flag++;
                    break;
                }
            }
            if (flag==0){
                errorList.add(JSON.toJSONString(exceptionHandVo));
                logger.info("文件处理依然失败:{}",JSON.toJSONString(exceptionHandVo));
            }
            long downEndTime = System.currentTimeMillis();    //获取结束时间
            logger.info("文件地址:{},下载耗时:{}ms,文件夹:{}",exceptionHandVo.getSourcePath(),(downEndTime - downStartTime),exceptionHandVo.getFileName());
        }

        long endTime = System.currentTimeMillis();    //获取结束时间
        logger.info("文件处理耗时:{}",(endTime - startTime));
        FileUtils.writer(errorList,logPath+"/exceptionHandError.txt");
    }

}
